package com.fuze.questionnaire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fuze.questionnaire.common.Advice;
import com.fuze.questionnaire.common.CustomException;
import com.fuze.questionnaire.domain.entity.Options;
import com.fuze.questionnaire.domain.entity.Problem;
import com.fuze.questionnaire.domain.entity.ProblemOptionsRelated;
import com.fuze.questionnaire.domain.entity.QuestionnaireProblemRelated;
import com.fuze.questionnaire.mapper.OptionsMapper;
import com.fuze.questionnaire.mapper.ProblemMapper;
import com.fuze.questionnaire.mapper.ProblemOptionsRelatedMapper;
import com.fuze.questionnaire.mapper.QuestionnaireProblemRelatedMapper;
import com.fuze.questionnaire.service.InsertionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author sepc_
 * @date 10/19/2021 09:47
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class InsertionServiceImpl implements InsertionService {

    final ProblemMapper problemMapper;

    final OptionsMapper optionsMapper;

    final ProblemOptionsRelatedMapper problemOptionsRelatedMapper;

    final QuestionnaireProblemRelatedMapper questionnaireProblemRelatedMapper;

    int superiorProblemId;

    @Override
    public boolean insertFromExcel(byte[] excel) {
        Workbook workbook = null;
        try (ByteArrayInputStream is = new ByteArrayInputStream(excel);) {
            workbook = WorkbookFactory.create(is);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("excel 文件读取失败");
        }
        if (workbook == null) {
            throw new CustomException(Advice.FAILED_READ_DATA);
        }
        Sheet sheet = workbook.getSheetAt(0);
        DataFormatter dataFormatter = new DataFormatter();
        // 行数
        int rowNum = sheet.getLastRowNum();
        for (int i = 0; i < rowNum + 1; i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            // 获取的最后一行的行数
            int cellNum = row.getLastCellNum();
            Problem problem = new Problem();
            //  获取数据
            Cell cell_0 = row.getCell(0);
            String value_0 = dataFormatter.formatCellValue(cell_0);
            problem.setProblem(value_0);

            Cell cell_1 = row.getCell(1);
            int value_1 = Integer.parseInt(dataFormatter.formatCellValue(cell_1));
            problem.setProjectTypeId(value_1);

            Cell cell_2 = row.getCell(2);
            String value_2 = dataFormatter.formatCellValue(cell_2);
            problem.setQuestionType(Integer.valueOf(value_2));

            Cell cell_3 = row.getCell(3);
            String value_3 = dataFormatter.formatCellValue(cell_3);
            if (!Objects.equals(value_3, "")) {
                problem.setSuperiorProblemId(this.superiorProblemId);
                problemMapper.insert(problem);
            } else {
                problemMapper.insert(problem);
                this.superiorProblemId = problem.getId();
            }
            // 存储到表
            for (int j = 4; j < cellNum + 1; j++) {
                Options options = new Options();
                Cell cell = row.getCell(j);
                String value = dataFormatter.formatCellValue(cell);
                if (value == null) {
                    continue;
                }
                Integer hasOption = checkHasOption(value.replace(" ", ""));
                if (null != hasOption) {
                    // 进到这里说明选项表已经有相同的答案，但是问题需要和该答案关联起来
                    // 关联问题和答案之后
                    ProblemOptionsRelated related = new ProblemOptionsRelated();
                    related.setProblemId(problem.getId());
                    related.setOptionsId(hasOption);
                    this.problemOptionsRelatedMapper.insert(related);
                    // 直接跳出循环
                    continue;
                }
                options.setOptions(value.replace(" ", ""));
                optionsMapper.insert(options);
                ProblemOptionsRelated related = new ProblemOptionsRelated();
                related.setProblemId(problem.getId());
                related.setOptionsId(options.getId());
                problemOptionsRelatedMapper.insert(related);
            }
            QuestionnaireProblemRelated related = new QuestionnaireProblemRelated();
            related.setQuestionnaireId(1);
            related.setProblemId(problem.getId());
            questionnaireProblemRelatedMapper.insert(related);
        }
        return true;
    }

    /**
     * 校验是否有重复的选项值
     * true - 存在 ； false - 不存在
     *
     * @param value 选项值
     * @return 校验结果
     */
    public Integer checkHasOption(String value) {
        QueryWrapper<Options> qw = new QueryWrapper<>();
        qw.eq(Options.COL_OPTIONS, value);
        List<Options> list = optionsMapper.selectList(qw);
        System.out.println("list.size() = " + list.size());
        if (list.size() > 0) {
            return list.get(0).getId();
        }
        return null;
    }

}
